package com.lagou.edu.interceptor;

import com.lagou.edu.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 陶肖寅
 * @version V1.0
 * @Package com.lagou.edu.inteceptor
 * @date 2020-02-02 16:53
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 */
public class SecurityInteceptor implements HandlerInterceptor {
    /**
     * 执行前先判断是否登录
     * 从session中获取用户信息
     * 判断是是存在
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //拦截请求请求判断是否已登录
        User user = (User)request.getSession().getAttribute("user");
        System.out.println(user);
        if(user!=null){
            //如果有数据，则继续执行
            return true;
        }
        //不符合条件的给出提示信息，并转发到登录页面
        request.setAttribute("msg", "您还没有登录，请先登录！");
        response.sendRedirect(request.getContextPath()+"/login");
//        if(user ==null) {
//            //如果未登录，则跳转到登录界面
//            response.sendRedirect(request.getContextPath()+"/login");
//            return true;
//        }
//        System.out.println("方法开始前执行");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
